<script setup lang="ts">
import { ref, unref } from 'vue'
import { BasicForm, useForm } from '@/components/Form'
import { dictTypeFormSchema, setDictTypeTreeParams } from '@/views/sys/dict/dict.data'
import { BasicModal, useModalInner } from '@/components/Modal'
import { dictTypeApi } from '@/api/sys/dictTypeApi'
import type { DictTypeAddReq, DictTypeUpdateReq } from '@/model/sys/dictTypeModel'

defineOptions({ name: 'DictTypeModal' })
const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true)

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: dictTypeFormSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    const values = data.record
    values.isUpdate = unref(isUpdate) ? '1' : ''
    setFieldsValue({ ...values })
    setDictTypeTreeParams({
      excludeDictTypeIds: [data.record.dictTypeId],
    })
  }
  else {
    setDictTypeTreeParams({})
  }
})

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    if (unref(isUpdate))
      await dictTypeApi.update(values as DictTypeUpdateReq)
    else await dictTypeApi.add(values as DictTypeAddReq)

    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    :min-height="300"
    :title="isUpdate ? '更新' : '新增'"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
